﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BD;
using Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Web.Oauth2;
using Web.Redis;
using Web.Util;
using Microsoft.AspNetCore.Http.Extensions;

namespace Web.Controllers
{
    /// <summary>
    /// 百度网盘oauth2接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class BaidupanController :MyBaseController<Object>
    {
        private IOptions<BDConfig> bdConfig;
        private MyRedisHelper redis;
        //百度账号信息   
        public BaidupanController(IOptions<BDConfig> bdConfig)
        {
            this.bdConfig = bdConfig;
            this.redis = MyRedisHelper.Instance();
        }
        /// <summary>
        /// 获取百度网盘授权地址
        /// <param name="type"> facebook, github, linkedin, oschina, qq, twitter, wechat, weibo, baidu</param>
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAuthorizeUrl")]
        public Result GetAuthorizeUrl()
        {
            OauthConnector c = OauthConnectorFactory.Build("baidu", bdConfig.Value.PanAppKey, bdConfig.Value.PanSecretKey);
            var uuid = Guid.NewGuid().ToString();
            redis.StringSet("session_baidupan_oauth_state", uuid, TimeSpan.FromSeconds(60));
            string url = c.GetAuthorizeUrl(uuid, Request.Scheme+"://"+Request.Host.Value+ "/api/baidupan/bind");
            return Result.Success().SetData(new { url = url });
        }
        /// <summary>
        /// 百度网盘回调地址
        /// </summary>
        /// <param name="state"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet("Bind")]
        public Result Bind(String state, String code)
        {
            var uuid = redis.StringGet("session_baidupan_oauth_state");
            if(String.IsNullOrEmpty(uuid) || uuid != state)
            {
                return Result.Error("参数state不正确");
            }
            if (String.IsNullOrEmpty(code) )
            {
                return Result.Error("参数code不存在");
            }
            OauthConnector c = OauthConnectorFactory.Build("baidu", bdConfig.Value.PanAppKey, bdConfig.Value.PanSecretKey);
            AccessToken a = c.GetAccessToken(code);
            return Result.Success().SetData(a);
        }
    }
}